/**
 * 初始化全局页面
 */
var APPID = 'wx19f1613f7ffa39be';       //微信公众号APPID
var BASE_URL = 'http://www.726bh9.cn'; //域名/ip
var REDIRECT_URI = window.location.pathname+window.location.search; 
var HTML_SCOPE = 'snsapi_userinfo';

function initGlobalPage() {
    // sessionStorage.clear();
    var token = sessionStorage.access_token;    //获取存储token
    if (token == null||token==undefined) {    //判断是否需要存在token
        var code = getQueryString('code');  //获取code
        if (code == null) {
            getUserCode(1); //获取code
            console.log('code')
        } else {
            ajaxGetToken(code); //获取token
            console.log('token')
        }
    }else{
        console.log('token已存在')
    }
}
/**
 * 获取查询字符串
 * @param name
 * @returns {null}
 */
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
/**
 * 获取用户code
 * @param state
 */
function getUserCode(state) {
    var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID + '&redirect_uri=' + BASE_URL + REDIRECT_URI + '&response_type=code&scope=' + HTML_SCOPE + '&state=' + state + '#wechat_redirect';
    // console.log(url);
    window.location.href = url;
}
// 重新获取token
function againToken() {
    // 清除所有键值
    sessionStorage.clear();
    initGlobalPage();
}
/**
 * 获取token
 * @param code
 */
function ajaxGetToken(code) {
    var data = {
        code:code
    };
    $.ajax({
        type: "get"
        , url: '/index/user/ajax_get_user_info'
        , data: data
        , async: false
        , success: function (req) {
            sessionStorage.setItem('access_token', req.data.token);
        }
        , error: function (resq) {
            console.info(resq);
            location.reload();
        }
    });
}

/**
 * 初始化用户信息
 */
function initUserInfo(vue, token) {
    var data = {
        token: token
    };
    $.get("/index/user/ajax_get_user_info_token", data, function (result) {
        console.info(result);
        if (result.code == 0) {
            againToken();
        }
        vue.user_info = result.data;
        user_id = result.data.id;
    });
}
function add0(m) {
    return m < 10 ? '0' + m : m
}
/**
 * 时间戳转换日期格式
 * @param val
 * @returns {string}
 */
function formatDate(val) {
    var time = new Date(val * 1000);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    // var h = time.getHours();
    // var mm = time.getMinutes();
    // var s = time.getSeconds();
    //return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
    return y + '-' + add0(m) + '-' + add0(d);
}